package com.cskaoyan.invocationhandler;

import com.cskaoyan.bean.JingTianInterface;

import java.lang.reflect.Method;

/**
 * 模仿JDK动态代理生成代理类我们去写代码
 * @author stone
 * @date 2021/12/24 11:40
 *
 * 1,实现了委托类所实现的接口
 * 2,和委托类相同定义的方法
 * 3,执行InvocationHandler的invoke
 */
public class JdkProxy implements JingTianInterface {
    Method m1;
    Method m2;
    Method m3;
    Method m4;
    Method m5;

    {
        try {
            m1 = Class.forName("com.cskaoyan.bean.JingTian").getDeclaredMethod("buyBreakFast");
            m2 = Class.forName("com.cskaoyan.bean.JingTian").getDeclaredMethod("buyLunch");
            m3 = Class.forName("com.cskaoyan.bean.JingTian").getDeclaredMethod("buySupper");
            m4 = Class.forName("com.cskaoyan.bean.JingTian").getDeclaredMethod("buyFood",String.class);
            m5 = Class.forName("com.cskaoyan.bean.JingTian").getDeclaredMethod("buyDoubleFood", String.class, String.class);

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    CustomInvocationHandler invocationHandler = new CustomInvocationHandler();

    @Override
    public void buyBreakFast() {
        try {
            invocationHandler.invoke(this,m1,null);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }

    @Override
    public void buyLunch() {
        try {
            invocationHandler.invoke(this,m2,null);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }

    }

    @Override
    public void buySupper() {
        try {
            invocationHandler.invoke(this,m3,null);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }

    }

    @Override
    public void buyFood(String food) {
        try {
            invocationHandler.invoke(this, m4, new Object[]{food});
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }

    @Override
    public void buyDoubleFood(String food1, String food2) {
        try {
            invocationHandler.invoke(this, m5, new Object[]{food1, food2});
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }
}
